import React from 'react'
import { useRoutes } from "react-router-dom"
import routes from "./index"

/**
 * 后端直接将路由映射表，返回给前端
 * 后端值返回路由名字，由前端自己去匹配
 * @returns 
 */
function DynamicRouter() {
    //筛选出符合要求路由，映射
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}")
    if (Object.keys(userInfo) != 0) {
        //userInfo = {role:{name:"超集管理员",menus:[]}}
        const {role:{menus = []}} = userInfo
        //menus = ["/home/user","/home/shop"]
        const userRoutes = menus.map(item=>{
            return item.substr(6)
        })
        const index = routes.findIndex(item=>item.path == "/home")
        let tempArray = [...routes[index].children]
        tempArray = tempArray.filter(item=>{
            if(userRoutes.includes(item.path) || item.index){
                return true
            }
        })
        console.log(tempArray);
        routes[index].children = tempArray

    }
    //这个地方筛选出你最终路由
    const element = useRoutes(routes)
    return element
}

export default DynamicRouter